import {APP_INITIALIZER, Component, Inject, Injectable, LOCALE_ID, OnInit} from '@angular/core';
import {_HttpClient, User} from '@delon/theme';
import {MenuItem, TreeNode} from 'primeng/api';
import {UtilityService} from '../../../service/utils.service';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {appConfig} from '../../../service/common';
import {AcMenuModule} from '../../../service/common.module';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.less']
})

// 依赖注入，把url链接注入进来即可
@Injectable()
export class MenuComponent implements OnInit {
    constructor(
        private http: _HttpClient,
        private utilityService: UtilityService,
        private nznot: NzNotificationService,
    ) { }

    treedata: any[]; // tree组件数据
    treemenus: MenuItem[]; // 右击菜单数据
    page: any;
    total: number;
    acmenuModule: AcMenuModule = new AcMenuModule();
    data: any[] = []; // 表格数据
    appData: any[]; // 应用数据
    guidParents =  [{
        'label': '',
        'guid': ''
    }]; // 父菜单
    isDisplay: boolean ;
    treeshow = false; // 是否显示树结构
    loading = false;
    nodrop: boolean;
    searchTitle: string;
    inforShow: boolean;
    isCancel: boolean; // 判断修改还是新增
    disableFlag: boolean;
    addMenuData: AcMenuModule = new AcMenuModule(); // 弹窗页面用的对象
    acMenuInfor: AcMenuModule = new AcMenuModule(); // 详细信息展示用的对象
    modalVisible= false;
    select: any;
    proDisable: boolean; // 增加页面时控制字段是否失去焦点
    proParentDisable: boolean; // 增加页面时控制父菜单字段是否失去焦点
    guidFuncshow: boolean; // 弹窗里控制功能字段是否可见
    proLeafDisable: boolean; // 弹窗里控制叶子菜单字段是否可输入
    guidParentsshow: boolean; // 弹窗里控制父菜单字段是否可见
    appcode: any; // 存储页面上应用ID 用来刷新页面
    originPonit: string; // 树拖拽时候的被拖拽菜单guid
    destinaPoint: string; // 树拖拽时候目标菜单的guid
    moveDate: any; // 移动菜单时候需要传的参数
    playOrder: any; // 菜单展示的顺序
    msgRq: string; // 查询接口
    Leafs = [
        {'text': '是' , 'value': 'Y'},
        {'text': '否' , 'value': 'N'}
    ];
    tanchuangTitle: string; // 弹窗名字
    guidFuncList: any; // 存储所有的功能
    menuType: string;
    options: any;
    selectionType: string; // 树结构类型

    ngOnInit() {
        this.isDisplay = true;
        this.acmenuModule.pi = 1;
        this.acmenuModule.size = 10;
        this.getAppData(); // 先查询应用信息
        this.selectionType = 'single';
        this.options = appConfig.Enumeration.iconoption;
    }

    // 查询有哪些应用
    getAppData() {
        this.page = {
            page: {
                current: 1,
                size: 100,
            }
        };
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.appListAll)
            .subscribe(
                (val) => {
                    this.appData = val.result;
                }
            );
    }

    // 递归拼接树结构
    iteration(node) {
        for (let i = 0; i < node.length; i++) {
            if (node[i].children !== undefined && node[i].children.length > 0) {
                node[i].label = node[i].showName;
                node[i].expandedIcon = 'anticon anticon-schedule';
                node[i].collapsedIcon = 'anticon anticon-schedule';
                node[i].childDict = true; // 是菜单组
                this.iteration(node[i].children); // 继续调用
            } else {
                node[i].label = node[i].showName;
                if(node[i].isleaf === '否') {
                    node[i].expandedIcon = 'anticon anticon-schedule';
                    node[i].collapsedIcon = 'anticon anticon-schedule';
                    node[i].childDict  =  true; // 是菜单组
                } else {
                    node[i].expandedIcon  = 'anticon anticon-tool';
                    node[i].collapsedIcon  = 'anticon anticon-tool';
                    node[i].childDict  =  false; // 是菜单
                }


            }
        }
    }


    // 查询应用菜单 new
    appCodeChanges(event, menuName?) {
        //  根据应用ID 查菜单
        // 拖拽属性
        this.nodrop = false ;
        this.searchTitle = '请搜索';
        this.appcode = event;
        // 调用服务来获取列表节点操作
        this.treedata = [];
        let objJson = {
            guidApp: event,
            menuName: '',
        }
        if(menuName) {
            objJson.menuName = menuName;
        }
        this.treedata = [ // 默认根节点
            {
                'label': '菜单结构',
                'data': 'Documents Folder',
                'guid': 'null',
                'expandedIcon': 'anticon anticon-home',
                'collapsedIcon': 'anticon anticon-home',
                'children': [{}]
            }
        ];
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.queryAcMenuFilterLists , objJson)
            .subscribe(
                (val) => {
                    if (val.code === '200' || val.code === 200) {
                        if (val.result.children !== undefined && val.result.children.length > 0) {
                            this.treedata[0].children = [val.result];
                        } else {
                            this.treedata[0].children = [val.result];
                        }
                        this.treeshow = true; // 显示树结构
                          this.iteration(this.treedata[0].children); // 递归更改树节点信息
                            this.treedata.forEach( node => {
                                this.expandRecursive(node, true);
                            });
                    }
                },
                (err) => {
                    this.nznot.create('error', err.msg , err.msg);
                });
    }


    // 选中了某个菜单,当它是叶子菜单的时候在页面的右边展示他的信息
    TreeSelect(event) {
        if (event.node.guid !== 'null') {
            this.acMenuInfor = event.node;
            this.inforShow = true;
            if(event.node.isleaf === '是') { // 代表是功能，显示功能对应的信息
                this.disableFlag = true; // 显示功能信息
            } else {
                this.disableFlag = false; // 不显示功能信息
            }
        } else {
            this.inforShow = false;
        }
    }

    // 右键单击文件夹名触发
    RightSelect(event) {
        this.select = event;
        if(event.node.guid === 'null') { // 跟菜单只能新增子菜单
            if(event.node.children[0].label) {
                this.treemenus = [
                    // 刷新都有 直接传入查询菜单的id玛
                    {label: '刷新', icon: 'anticon anticon-loading anticon-spin' , id: appConfig.funcObject.menu.queryMenu,command: () => this.appCodeChanges(this.appcode)},
                ];
            } else {
                this.treemenus = [
                    {label: '新增根菜单', icon: 'anticon anticon-plus' , id: appConfig.funcObject.menu.addMenu, command: () => this.addMenu('root')},
                ];
            }
        } else {
            if(this.select.node.childDict === true) { // 是菜单组，可以新增菜单，新增菜单组，删除菜单组
                this.treemenus = [
                    {label: '新增子菜单', icon: 'anticon anticon-plus' ,id: appConfig.funcObject.menu.addChildMenu, command: () => this.addMenu('rootchild')},
                    {label: '新增菜单', icon: 'anticon anticon-plus-circle' , id: appConfig.funcObject.menu.addChildMenu,command: () => this.addMenu('child')},
                    {label: '修改菜单', icon: 'fa fa-edit' , id: appConfig.funcObject.menu.editMenu,command: () => this.updateMenu()},
                    {label: '删除菜单', icon: 'anticon anticon-close', id: appConfig.funcObject.menu.delMenu,command: () => this.delectMenu()}
                ];
            }else{ // 是菜单，可以修改菜单，删除菜单
                this.treemenus = [
                    {label: '修改菜单', icon: 'fa fa-edit' , id: appConfig.funcObject.menu.editMenu, command: () => this.updateMenu()},
                    {label: '删除菜单', icon: 'anticon anticon-close', id: appConfig.funcObject.menu.delMenu, command: () => this.delectMenu()},

                ];
            }

        }

    }

    delectMenu() {
        this.addMenuData = new AcMenuModule();
        this.guidParents[0].label = this.select.node.menuName;
        this.guidParents[0].guid = this.select.node.guid;
        this.addMenuData.guidParents = this.select.node.guid;
        this.addMenuData.guidApp = this.select.node.guidApp;
        this.addMenuData.menuName = this.select.node.menuName;
        this.addMenuData.menuLabel = this.select.node.menuLabel;
        this.addMenuData.guidFunc = this.select.node.guidFunc;
        this.addMenuData.menuCode = this.select.node.menuCode;
        this.addMenuData.isLeaf = this.select.node.isleaf;
        this.proParentDisable = false;
        this.proDisable = true ;
        this.utilityService.deleatData(appConfig.serverUrl  + appConfig.API.acMenuDeletByid + this.select.node.guid)
            .subscribe(
                (val) => {
                    this.nznot.create('success', val.msg , val.msg);
                    this.appCodeChanges(this.appcode);
                },
                (err) => {
                    this.nznot.create('error', err.msg , err.msg);
                    this.appCodeChanges(this.appcode);
                }
            );
        // this.appCodeChange(this.appcode );
    }

    // 查询所有功能
    queryFunc() {
        // 增加菜单前 查询所有的功能
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.funcAdd + '/' + this.appcode + '/getFuncByApp')
            .subscribe(
                (val) => {
                    this.guidFuncList = val.result;
                },
                (err) => {
                    this.nznot.create('error', err.msg , err.msg);
                }
            );
    };

    addMenu(ischild) {
        this.addMenuData = new AcMenuModule();
       if(ischild === 'rootchild') { // 新增子菜单
           this.tanchuangTitle = '增加子菜单';
           this.menuType = 'rootchild'
           this.guidFuncshow = false;
           this.addMenuData.isLeaf = 'N'; // 默认不是，是新增子菜单
       } else if(ischild === 'root') {
           this.tanchuangTitle = '增加跟菜单';
           this.menuType = 'root'
           this.addMenuData.isLeaf = 'N'; // 默认不是，是新增子菜单
           this.guidFuncshow = false;
       } else {
           this.tanchuangTitle = '增加菜单';
           this.menuType = 'child';
           this.guidFuncshow = true;
           this.queryFunc();
           this.addMenuData.isLeaf = 'Y'; // 默认不是，是新增子菜单
       }
        this.modalVisible = true;
        this.isCancel = true;
        this.guidParents[0].label = this.select.node.menuName;
        this.guidParents[0].guid = this.select.node.guid;
        this.addMenuData.guidParents = this.select.node.guid;
        this.addMenuData.guidApp = this.select.node.guidApp;
    }

    updateMenu() {
        console.log(this.select.node)
        this.queryFunc(); // 查询所有功能
        this.menuType = 'child';
        this.tanchuangTitle = '修改菜单';
        this.isCancel = true;
        this.modalVisible = true;
        // 修改菜单叶子菜单字段不可输入
        this.proLeafDisable = true;
        // 修改菜单父菜单字段不可见
        this.guidParentsshow = false;
        this.addMenuData = new AcMenuModule();
        // 最底层菜单才能修改功能
        if (this.select.node.isleaf === '是') {
            this.guidFuncshow = true;
            this.addMenuData.guidFunc = this.select.node.guidFunc;
        }else {
            // 控制功能字段是否可见
            this.guidFuncshow = false;

        }
        this.addMenuData.isLeaf = this.select.node.isleaf;
        this.addMenuData.guidApp = this.select.node.guidApp;
        this.addMenuData.guidParents = this.select.node.guidParents;
        this.addMenuData.menuName = this.select.node.menuName;
        this.addMenuData.menuLabel = this.select.node.menuLabel;
        this.addMenuData.menuCode = this.select.node.menuCode;
        this.addMenuData.guidFunc = this.select.node.guidFunc;
        this.addMenuData.guid = this.select.node.guid;
        this.addMenuData.imagePath = this.select.node.imagePath;
        this.addMenuData.uiEntry = this.select.node.uiEntry;
        this.addMenuData.displayOrder = this.select.node.displayOrder;
        this.addMenuData.createtime = this.select.node.createtime;
        this.addMenuData.expandPath = this.select.node.expandPath;
        this.addMenuData.guidRoot = this.select.node.guidRoot;
        this.addMenuData.menuLevel = this.select.node.menuLevel;
        this.addMenuData.menuSeq = this.select.node.menuSeq;
        this.addMenuData.openMode = this.select.node.openMode;
        this.addMenuData.showName = this.select.node.showName;

        this.proParentDisable = false;
        this.proDisable = false ;
        // console.log(this.select.node.imagePath);
    }

    // 弹窗页面的确认方法
    save () {
        if(this.isCancel) { // 存在 才是新增和修改的逻辑
            this.modalVisible = false;
            console.log(this.menuType);
            if(this.menuType === 'child' || this.menuType === 'rootchild') {
                // 枚举值转换
                if (this.tanchuangTitle === '修改菜单') {
                    if (this.addMenuData.isLeaf === '是') {
                        this.addMenuData.isLeaf = 'Y';
                    } else {
                        this.addMenuData.isLeaf = 'N';
                    }
                    console.log(this.addMenuData)
                    this.utilityService.putData(appConfig.serverUrl  + appConfig.API.acMenuUpdate , this.addMenuData)
                        .subscribe(
                            (val) => {
                                this.appCodeChanges(this.appcode );
                                this.nznot.create('success', val.msg , val.msg);
                            },
                            (err) => {
                                this.nznot.create('error', err.msg , err.msg);
                            }
                        );
                }
                if (this.tanchuangTitle === '增加子菜单' || this.tanchuangTitle === '增加菜单') {
                    this.addMenuData.guidApp = this.appcode;
                    this.utilityService.postData(appConfig.serverUrl  + appConfig.API.acMenuAddChild, this.addMenuData)
                        .subscribe(
                            (val) => {
                                // this.appCodeChange(this.appcode );
                                this.appCodeChanges(this.appcode );
                                this.nznot.create('success', val.msg , val.msg);
                            },
                            (err) => {
                                this.nznot.create('error', err.msg , err.msg);
                            }
                        );
                }

                this.guidFuncshow = false;
            } else { // 调用根菜单
                this.addMenuData.guidApp = this.appcode;
                this.utilityService.postData(appConfig.serverUrl  + appConfig.API.acRootMenu , this.addMenuData)
                    .subscribe(
                        (val) => {
                            // this.appCodeChange(this.appcode);
                            this.appCodeChanges(this.appcode);
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (err) => {
                            this.nznot.create('error', err.msg , err.msg);
                        }
                    );
                this.guidFuncshow = false;
            }
        }
    }

    viewFile() {
        alert('点我1');
    }

    unselectFile() {
        alert('电你1');
    }


    close() {
        alert('改变');
    }


    dropEvent($event) {
        this.originPonit = $event.dragNode.guid;
        this.destinaPoint = $event.dropNode.guid;
        // 如果拖拽的目的地菜单是叶子菜单，拖拽目标目的地设为它的父菜单
        if ($event.dropNode.isleaf === 'Y') {
            this.destinaPoint = $event.dropNode.guidParents;
        }
        this.playOrder = $event.dragNode.displayOrder;
        this.moveDate = {
            'targetGuid': this.destinaPoint,
            'moveGuid': this.originPonit,
            'order': 0
        };
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.acMenuMove , this.moveDate )
            .subscribe(
                (val) => {
                    this.nznot.create('success', '拖拽成功' , '拖拽成功');
                    this.appCodeChanges(this.appcode);
                },
                (err) => {
                    this.nznot.create('error', err.msg , err.msg);
                    this.appCodeChanges(this.appcode);
                }
            );
        this.guidFuncshow = false;
    }



    // 展开所有树节点的方法
    private expandRecursive(node: TreeNode, isExpand:boolean){
        node.expanded = isExpand;
        if(node.children){
            node.children.forEach( childNode => {
                this.expandRecursive(childNode, isExpand);
            } );
        }
    }

    searchVal($event) {
        this.appCodeChanges(this.appcode, $event );
    }


    // 树按钮的三个方法
    clickFunc($event) {
        if ($event === 'reset') {
            this.appCodeChanges(this.appcode );
        } else if($event === 'expand') { // 全部展开方法
            this.inforShow = true;
            // 展开所有的
            this.treedata.forEach( node => {
                this.expandRecursive(node, true);
            } );
        } else {
            this.inforShow = false;
        }
    }


    // 关闭弹窗的方法
    menuCancel() {
        this.modalVisible = false; // 关闭弹窗
        this.isCancel = false;
    }
}
